package r.comment.comm;

import org.eclipse.core.resources.IFile;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchWindow;

public class Comm {
	private String strForTab="    ";//用来替换tab的空格，默认四个
	
	public IEditorPart getEditorPart(IWorkbenchWindow window) {
		IEditorPart ep = window.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
		return ep;
	}


	public boolean isJspComment(IWorkbenchWindow window, String selectLine) {
		IEditorPart ep = getEditorPart(window);

		IEditorInput ei = ep.getEditorInput();
		IFile file = ((IFileEditorInput) ei).getFile();

		String fileName = file.getName();
		String fileType;
		try {
			fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		}
		catch (Exception e) {
			fileType = "java";
			e.printStackTrace();
		}

		selectLine = selectLine.replace(" ", "");
		boolean jspFlg = false;
		if ((fileType.toUpperCase().equals("JSP")) && ((selectLine.indexOf("<") >= 0) || (selectLine.indexOf("  <") > 0) || (selectLine.indexOf("\t<") > 0)) && ((selectLine.length() - selectLine.lastIndexOf(">") == 3) || (selectLine.length() - selectLine.lastIndexOf(">") == 2)) && (selectLine.length() != 2)) {
			jspFlg = true;
		}
		return jspFlg;
	}

	public String getLeftTabAddStr(String text) {
		if(text.trim().equals("")){
			return text;
		}
		
		String[] s=text.replaceAll("(\\S+.*\\S+)", "W").split("W");
		if(s.length==0){
			return "";
		}
		return text.substring(0, s[0].length());
	}
	
	public String replaceLeftTabToStr(String text){
		if(text.trim().equals("")){
			return text.replace("\t", strForTab);
		}
		
		String leftTabAddStr=getLeftTabAddStr(text);
		text=leftTabAddStr.replace("\t", strForTab)+text.substring(leftTabAddStr.length());
		
		return text;
	}

}